package com.college.eduService.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.college.commonutil.jwt.JwtUtils;
import com.college.commonutil.result.Result;
import com.college.eduService.client.OrderClient;
import com.college.eduService.entity.EduCourse;
import com.college.eduService.entity.frontvo.CourseWebVo;
import com.college.eduService.entity.vo.ChapterVo;
import com.college.eduService.entity.frontvo.CourseFrontVo;
import com.college.eduService.service.EduChapterService;
import com.college.eduService.service.EduCourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/eduservice/courseFront")
public class CourseFrontController {

    @Autowired
    EduCourseService courseService;
    @Autowired
    private EduChapterService eduChapterService;
    @Autowired
    OrderClient orderClient;

    @PostMapping("getConditionPage/{page}/{limit}")
    public Result GetPageCourse(@PathVariable int page, @PathVariable int limit,
                                @RequestBody CourseFrontVo courseFrontVo){
        Page<EduCourse> coursePage = new Page<>(page, limit);

        Map<String,Object> map = courseService.getCourseFrontInfo(coursePage,courseFrontVo);

        //返回分页中的所有数据
        return Result.ok().data(map);
    }

    //课程详情的方法
    @GetMapping("/getFrontCourseInfo/{courseId}")
    public Result getFrontCourseInfo(@PathVariable String courseId, HttpServletRequest request){
        boolean isBuyCourse = false;
        //根据课程id，编写sql语句查询课程信息
        CourseWebVo courseWebVo = courseService.getBaseCourseInfo(courseId);

        //根据课程id，查询章节和小节信息
        List<ChapterVo> chapterVideoList = eduChapterService.getChapterVideoByCourseId(courseId);
        //获取用户id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (!StringUtils.isEmpty(memberId)){
            //根据课程id、用户id，查询课程是否已经购买
            isBuyCourse = orderClient.isBuyCourse(memberId, courseId);
        }

        return Result.ok().data("courseWebVo",courseWebVo).data("chapterVideoList",chapterVideoList).data("isBuy",isBuyCourse);

    }
}
